package com.qcc.cashier.print;

import com.landicorp.android.eptapi.device.Printer;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;

public class PrintHelper {

    private MyProcess myProcess;

    public PrintHelper() {
        myProcess = new MyProcess();
        myProcess.addStep(printer -> {
            // Make the print method can print more than one line.
            printer.setAutoTrunc(true);
            // Default mode is real mode, now set it to virtual mode.
//            printer.setMode(Printer.MODE_VIRTUAL);
        });
    }

    public Observable<Boolean> startPrint(String imgPath) {
        return Observable.create(emitter -> {
            myProcess.setEmitter(emitter);
            myProcess.setPrintContent(imgPath);
            myProcess.start();
        });
    }

    private class MyProcess extends Printer.Progress {

        private String imgPath;
        private ObservableEmitter emitter;

        private void setEmitter(ObservableEmitter emitter) {
            this.emitter = emitter;
        }

        public void setPrintContent(String imgPath) {
            this.imgPath = imgPath;
        }

        @Override
        public void doPrint(Printer printer) throws Exception {
            printer.printImage(Printer.Alignment.CENTER, this.imgPath);
        }

        @Override
        public void onFinish(int code) {
            if (code == Printer.ERROR_NONE) {
                emitter.onNext(true);
                emitter.onComplete();
            } else {
                emitter.onError(new Throwable(Printer.getErrorDescription(code)));
            }
        }

        @Override
        public void onCrash() {
//            emitter.onError(new Throwable("远程出错"));
            emitter.onNext(false);
        }
    }


}
